package com.xxd.gulimail.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxd.common.constant.ProductConstant;
import com.xxd.gulimail.product.dao.AttrAttrgroupRelationDao;
import com.xxd.gulimail.product.dao.AttrGroupDao;
import com.xxd.gulimail.product.dao.CategoryDao;
import com.xxd.gulimail.product.entity.AttrAttrgroupRelationEntity;
import com.xxd.gulimail.product.entity.AttrGroupEntity;
import com.xxd.gulimail.product.entity.CategoryEntity;
import com.xxd.gulimail.product.service.AttrAttrgroupRelationService;
import com.xxd.gulimail.product.service.CategoryService;
import com.xxd.gulimail.product.vo.AttrGroupRelationVo;
import com.xxd.gulimail.product.vo.AttrVo;
import com.xxd.gulimail.product.vo.AttrespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxd.common.utils.PageUtils;
import com.xxd.common.utils.Query;

import com.xxd.gulimail.product.dao.AttrDao;
import com.xxd.gulimail.product.entity.AttrEntity;
import com.xxd.gulimail.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Resource
    AttrAttrgroupRelationService relationService;
    @Resource
    AttrAttrgroupRelationDao relationDao;
    @Resource
    AttrGroupDao attrGroupDao;
    @Resource
    CategoryDao categoryDao;
    @Resource
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @Description:
     * @Author: xuxd
     * @param :Params:page,limit,key:
     * @param attrType:[0-销售属性 sale，1-基本属性 base]
     * @Date: 2022/10/16 20:13
     */
    @Override
    public PageUtils findPage(Map<String, Object> params, Long catelogId, String attrType) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(obj->{
            obj.eq("attr_id",key).or().like("attr_name",key);});
        }
        if (catelogId > 0){
            wrapper.eq("catelog_id",catelogId);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),wrapper);
        List<AttrEntity> records = page.getRecords();//获取查询到的值
        //获取展示的视图对象,并注入
        List<AttrespVo> attrespVoList = records.stream().map(obj -> {
            AttrespVo vo = new AttrespVo();
            BeanUtils.copyProperties(obj, vo);
            //1.设置分类名称和分组名称
            String attrGroupName = "";
            String CatelogName = "";
            //2.从关联中间表获取分组对象id
            AttrAttrgroupRelationEntity attrId = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", vo.getAttrId()));
            if (attrId != null) {//根据分组id查询出分组名称
                attrGroupName = attrGroupDao.selectById(attrId.getAttrGroupId()).getAttrGroupName();
            }
            //3.根据CatelogId获取分类名称
            CategoryEntity categoryEntity = categoryDao.selectById(vo.getCatelogId());
            if (categoryEntity != null) {
                CatelogName = categoryEntity.getName();
            }
            //4.注入视图对象返回
            vo.setCatelogName(CatelogName);
            vo.setGroupName(attrGroupName);
            return vo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrespVoList);
        return pageUtils;
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);//在变量名一致的前提下，将attr的值注入给attrEntity
        this.save(attrEntity);//保存基础数据
        //保存关联关系
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationService.save(relationEntity);
        }
    }

    //返回AttrespVo中的catelogPath分类和分组信息groupName
    @Override
    public AttrespVo getAttrInfo(Long attrId) {
        String groupName = "";
        Long attrGroupId = null;
        //1.获取表中信息，查询catelogPath,根据中间表查询分组id,
        AttrEntity attrEntity = this.getById(attrId);
        Long[] path = categoryService.getcatelogPath(attrEntity.getCatelogId());
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relationEntity != null){//中间表获取分组id
             attrGroupId = relationEntity.getAttrGroupId();
            //2.根据分组id查询分组表信息
            AttrGroupEntity groupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrGroupId));
            if (groupEntity != null){
                groupName = groupEntity.getAttrGroupName();
            }
        }
        //3.注入catelogPath,和attrEntity,groupName,返回
        AttrespVo vo = new AttrespVo();
        BeanUtils.copyProperties(attrEntity,vo);
        vo.setCatelogPath(path);
        vo.setGroupName(groupName);
        vo.setAttrGroupId(attrGroupId);
        return vo;
    }

    /**
     * @Description: 修改规格参数
     * @Author: xuxd
     * @Date: 2022/10/17 12:29
     * 1.基本修改（表）,销售属性修改表，不无联合表
     * 2.判断关联表中是否有记录，有：修改 无：新增
     * 3.新增，修改分组关联（group_id）
     */
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //1.基本修改（表）
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){//销售属性修改表，不无联合表
            Long attrGroupId = attr.getAttrGroupId();
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            //2.判断关联表中是否有记录，有：修改 无：新增
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0){//有：修改 3.根据attr_id修改分组关联表（attr_group_id）,
                relationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()).set("attr_group_id",attrGroupId));
            }else{//无：新增
                relationEntity.setAttrId(attr.getAttrId());
                relationEntity.setAttrGroupId(attrGroupId);
                relationDao.insert(relationEntity);
            }
        }


    }

    /**
     * @Description: 根据分组Id获取关联关系
     * @Author: xuxd
     * @Date: 2022/10/17 15:51
     */
    @Override
    public List<AttrEntity> getRelationAttr(long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if (entities.size()>0){
            List<Long> attrIds = entities.stream().map(obj -> {
                Long attrId = obj.getAttrId();
                return attrId;
            }).collect(Collectors.toList());

            List<AttrEntity> attrEntities = (List<AttrEntity>) this.listByIds(attrIds);
            return attrEntities;
        }else{
            return null;
        }

    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
//  relationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",1L).eq("attr_group_id",1L));
        //批量删除
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map(obj -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(obj, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(entities);
    }

    /**
     * @Description: 获取当前分组没有关联的所有属性并分页
     * @Author: xuxd
     * @param
     * @Date: 2022/10/17 17:36
     */
    @Override
    public PageUtils getNoAttrRelationAttr(Map<String, Object> params, long attrgroupId) {
        //1.当前分组只能关联自己所属的分类里面的属性
        AttrGroupEntity groupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = Long.valueOf(0);
        if (groupEntity != null){
             catelogId = groupEntity.getCatelogId();
        }
        //2.当前分组只能关联同一分类下别的分组没有被引用的属性
        //2.1 查询当前分类下其它分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));
        List<Long> list = null;
        if (group.size()>0){
             list = group.stream().map(obj -> {
                Long groupId = obj.getAttrGroupId();
                return groupId;
            }).collect(Collectors.toList());
        }
        //2.2这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", list));
        List<Long> collect = relationEntities.stream().map(obj -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        //2.3从当前属性（）中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).eq("catelog_id", catelogId);
        if(collect!=null && collect.size()>0){
            wrapper.notIn("attr_id", collect);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(w->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),wrapper);
        return new PageUtils(page);
    }

    /**
     * @Description: 新增关联
     * @Author: xuxd
     * @param vos:新增对象
     * @Date: 2022/10/17 19:56
     */
    @Override
    public void saveRelation(AttrGroupRelationVo[] vos) {
        List<AttrGroupRelationVo> vo = Arrays.asList(vos);
        List<AttrAttrgroupRelationEntity> relationEntities = vo.stream().map(obj -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(obj, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationService.saveBatch(relationEntities);
    }

}